package com.qyapp.sdkplatform.sdk;

import android.app.Activity;
import android.content.Intent;
import android.os.Handler;
import android.os.Message;
import android.widget.Toast;

import com.tencent.mm.opensdk.modelbase.BaseResp;
import com.tencent.mm.opensdk.modelmsg.SendAuth;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.IWXAPIEventHandler;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;

import org.json.JSONObject;

import java.io.IOException;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

/**
 * Created by 2ustc on 2017/6/27.
 */

public class WechatPlatform extends Platform {
    static WechatPlatform platform;
    String mAppid;
    String mSecret;
    IWXAPI mWxapi;
    String mCode;
    String mAccessToken;
    OkHttpClient httpClient;
    Handler mHandler;

    static final int MSG_SUCCESS = 0;
    static final int MSG_CANCEL = 1;
    static final int MSG_FAILD = 2;

    public static WechatPlatform share() {
        return platform == null ? (platform = new WechatPlatform()) : platform;
    }


    @Override
    public void init(Activity activity, final IPlatformCallback callback, String... args) {
        super.init(activity, callback, args);
        this.mAppid = args[0];
        this.mSecret = args[1];
        this.mWxapi = WXAPIFactory.createWXAPI(activity, mAppid, false);
        this.mWxapi.registerApp(this.mAppid);
        this.mHandler = new Handler() {

            @Override
            public void handleMessage(Message msg) {
                if (mPlatformCallback != null) {
                    switch (msg.what) {
                        case MSG_SUCCESS:
                            mPlatformCallback.onAuthSuccess((JSONObject) msg.obj, WechatPlatform.this);
                            break;
                        case  MSG_FAILD:
                            mPlatformCallback.onAuthFaild(-1,msg.obj.toString());
                            break;
                        case  MSG_CANCEL:
                            mPlatformCallback.onAuthCancel();
                            break;
                    }
                }
            }
        };

    }

    @Override
    public void login() {
        if (!mWxapi.isWXAppInstalled()) {
            Toast.makeText(mActivity, "微信没有安装!", Toast.LENGTH_SHORT).show();
            return;
        }
        if (mWxapi != null) {
            SendAuth.Req req = new SendAuth.Req();
            req.scope = "snsapi_userinfo";
            req.state = "wechat_sdk_demo_test";
            mWxapi.sendReq(req);
        }
    }

    @Override
    public void destroy() {
        platform = null;
        httpClient = null;
        mHandler=null;
    }

    public void handleIntent(Intent intent, IWXAPIEventHandler handler) {
        this.mWxapi.handleIntent(intent, handler);
    }

    public void onResp(BaseResp resp) {
        SendAuth.Resp authResp = ((SendAuth.Resp) resp);
        if (resp != null && resp.errCode == BaseResp.ErrCode.ERR_OK) {
            mCode = authResp.code;
            getAccessToken();
        } else if (mPlatformCallback != null) {
            if (authResp.errCode == BaseResp.ErrCode.ERR_USER_CANCEL) {
                mPlatformCallback.onAuthCancel();
            } else {
                mPlatformCallback.onAuthFaild(resp.errCode, null);
            }
        }
    }

    private void getAccessToken() {
        if (httpClient == null) {
            httpClient = new OkHttpClient();
        }
        Request request = new Request.Builder()
                .url(String.format("https://api.weixin.qq.com/sns/oauth2/access_token?appid=%s&secret=%s&code=%s&grant_type=authorization_code", mAppid, mSecret, mCode))
                .build();
        httpClient.newCall(request)
                .enqueue(new Callback() {
                    @Override
                    public void onFailure(Call call, IOException e) {
                       mHandler.obtainMessage(MSG_FAILD,e.getMessage()).sendToTarget();
                    }

                    @Override
                    public void onResponse(Call call, Response response) throws IOException {
                        if (response.isSuccessful()) {
                            String ret = response.body().string();
                            try {
                                JSONObject json = new JSONObject(ret);
                                mAccessToken = json.getString("access_token");
                                mOpenId = json.getString("openid");
                                getUserInfo();
                            } catch (Exception e) {
                               mHandler.obtainMessage(MSG_FAILD,e.getMessage()).sendToTarget();
                            }

                        }
                    }
                });
    }

    private void getUserInfo() {
        final Request request = new Request.Builder()
                .url(String.format("https://api.weixin.qq.com/sns/userinfo?access_token=%s&openid=%s", mAccessToken, mOpenId))
                .build();
        httpClient.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                mHandler.obtainMessage(MSG_CANCEL,e.getMessage()).sendToTarget();
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                if (response.isSuccessful()) {
                    String ret = response.body().string();
                    try {
                        JSONObject json = new JSONObject(ret);
                        mHandler.obtainMessage(MSG_SUCCESS, json).sendToTarget();
                    } catch (Exception e) {
                        mHandler.obtainMessage(MSG_FAILD, e.getMessage()).sendToTarget();
                    }
                }
            }
        });
    }
}
